﻿using System;
using System.Threading;
using System.Web.Configuration;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using RequireHttps;

namespace KeepAlive
{
    public class KeepAliveController : ApiController
    {
        public const string UriKeepAlive = "api/KeepAlive";
        private static string uriHost;
        private static Timer timer;

        [HttpGet]
        [RequireHttps]
        [Route(UriKeepAlive)]
        public IHttpActionResult KeepAliveCallback()
        {
            return Ok();
        }

        static KeepAliveController()
        {
            int timeoutInMs = -1;

            try
            {
                timeoutInMs = int.Parse(WebConfigurationManager.AppSettings["KeepAliveTimeoutInSec"]) * 1000;
            }
            catch { }

            if (timeoutInMs > 0)
                timer = new Timer(_ => KeepAlive(), null, 0, timeoutInMs);
        }

        public static void InitKeepAlive(HttpApplication app)
        {
            if (app == null)
                return;

            UriHost = app.Context.Request.Url.GetLeftPart(UriPartial.Authority);
        }

        private static string UriHost
        {
            get
            {
                lock (typeof(KeepAliveController))
                    return uriHost;
            }
            set
            {
                lock (typeof(KeepAliveController))
                {
                    if (string.IsNullOrEmpty(uriHost))
                        uriHost = value;
                }
            }
        }

        private static async void KeepAlive()
        {
            if (!string.IsNullOrEmpty(UriHost))
                using (var httpClient = new HttpClient())
                    await httpClient.GetAsync(string.Format("{0}/{1}", UriHost, UriKeepAlive));
        }
    }
}
